﻿#region License
//  Distrubted Under the GNU Public License version 2 (GPLv2)
// ========================================
// 
//  QuizzMasterStudio Version 3 
//  Copyright © 2012 , The Sparks (Autism App Jam 2014)
//  All rights reserved.  
// 
// Robert Long, Zephyr Yao, Hillary Chansavang, Li Xiao, Arial Xiao
// 
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//  
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//  
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
//  The full license is also included in the root folder.
// 
// Robert Long
//  Email: rbtLong@live.com
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using Core.Util;

namespace Core.Features.FillIn.ViewModel
{
    public class DigitScrambler
    {
        private int[] _possibilities;
        private readonly int _correctValue;
        private int _correctIdx;

        public int[] Possibilities { get { return _possibilities; } }
        public int CorrectValue { get { return _correctValue; } }
        public int CorrectIdx { get { return _correctIdx; } }

        public DigitScrambler(int correctValue)
        {
            _correctValue = correctValue;
            scramble();
        }

        private void scramble()
        {
            _possibilities = generateRandomDigits(4);
            findOrInsertCorrectValue(_possibilities);
        }

            private void findOrInsertCorrectValue(int[] possible)
            {
                var idx = Array.IndexOf(possible, _correctValue);
                if (idx == -1)
                {
                    var n = GlobalRandomizer.Rnd.Next(0, 4);
                    possible[n] = _correctValue;
                    _correctIdx = n;
                }
                else
                    _correctIdx = idx;
            }

            private int[] generateRandomDigits(int max)
            {
                var possible = new List<int>(max);
                do
                {
                    var n = GlobalRandomizer.Rnd.Next(0, 9);
                    if (possible.All(o => o != n))
                        possible.Add(n);
                } while (possible.Count < max);
                return possible.ToArray();
            }
    }
}
